//
//  UIScrollView+SJSnapshot.m
//  WSL
//
//  Created by CJ on 2018/1/11.
//  Copyright © 2018年 sanjuetech. All rights reserved.
//

#import "UIScrollView+SJSnapshot.h"

@implementation UIScrollView (SJSnapshot)

- (UIImage *)getLongShotsImageView {
    
    NSMutableArray *imgArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    NSInteger total = ceilf(self.contentSize.height/self.frame.size.height);
    
    CGSize size = CGSizeZero;
    for (NSInteger i = 0; i < total; ++i)
    {
        [self setContentOffset:CGPointMake(0, i*self.frame.size.height)]
        ;
        if (i == total-1) {
            size = CGSizeMake(self.frame.size.width, self.contentSize.height- i*self.frame.size.height);
            
        } else {
            size = self.frame.size;
        }
        
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, -self.contentOffset.x, -self.contentOffset.y);
        
        [self.layer renderInContext:context];
        
        CGContextRestoreGState(context);
        
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        [imgArray addObject:img];
        
        UIGraphicsEndImageContext();
    }
    
    // 拼接
    UIImage *image = imgArray[0];
    if (imgArray.count == 1) {
        return image;
    }
    
    for (NSInteger i = 1; i < imgArray.count; i++)
    {
        image = [self combineWithTopImage:image BottomImage:imgArray[i]  ImageSacle:[UIScreen mainScreen].scale];
        if (i == imgArray.count-1) {
            break;
        }
    }
    
    return image;
    
}

- (UIImage *)combineWithTopImage:(UIImage*)image1 BottomImage:(UIImage*)image2 ImageSacle:(CGFloat)imageSacle {
    
    CGFloat w = image1.size.width;
    CGFloat h = image1.size.height + image2.size.height;
    
    CGSize offSize = CGSizeMake(w, h);
    
    UIGraphicsBeginImageContextWithOptions(offSize, NO, imageSacle);
    
    CGRect rect1 = CGRectMake(0, 0, w, image1.size.height);
    
    
    [image1 drawInRect:rect1];
    
    
    CGRect rect2 = CGRectMake(0, rect1.origin.y+image1.size.height, w, image2.size.height);
    [image2 drawInRect:rect2];
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
    
}


@end
